package gold.digger;

import gold.utils.InputUtil;

import java.util.*;

/**
 * Created by fanzhenyu02 on 2021/12/10.
 * common problem solver template.
 */
public class LC719 {
    public long startExecuteTime = System.currentTimeMillis();


    /*
     * @param 此题目参考了别人代码
     * 这是因为问题情况较为复杂
     * 未来需要再次复习此道题目
     * 这道hard难度又点意思，可以以后再仔细想想
     * @return:
     */
    public class Solution {

        public int smallestDistancePair(int[] nums, int k) {
            Arrays.sort(nums);
            int len = nums.length;
            int left = 0;
            int right = nums[len - 1] - nums[0];
            while (left < right) {
                int mid = (left + right) / 2;
                int count = countLessEquals(nums, mid);
                if (count < k) {
                    // 如果小于等于 mid 的个数严格小于 k 个，说明 mid 太小了
                    // 下一轮搜索区间为 [mid + 1..right]
                    left = mid + 1;
                } else {
                    // 下一轮搜索区间为 [left..mid]
                    right = mid;
                }
            }
            return left;
        }

        /**
         * 统计距离（数值之差的绝对值）小于等于 threshold 的个数
         *
         * @param nums
         * @param threshold
         * @return
         */
        private int countLessEquals(int[] nums, int threshold) {
            int count = 0;
            int len = nums.length;
            for (int left = 0, right = 0; right < len; right++) {
                while (nums[right] - nums[left] > threshold) {
                    left++;
                }
                // 此时满足 nums[right] - nums[left] <= threshold
                // right 与 [left..right - 1] 里的每一个元素的「距离」都小于等于 threshold
                // [left..right - 1] 里元素的个数为 right - left
                count += right - left;
            }
            return count;
        }
    }


    public void run() {
        int[] arr = InputUtil.toIntegerArray("[1,2,3]");
        System.out.println(new Solution().toString());
    }

    public static void main(String[] args) throws Exception {
        LC719 an = new LC719();
        an.run();

        System.out.println("\ncurrent solution total execute time: " + (System.currentTimeMillis() - an.startExecuteTime) + " ms.");
    }
}
